package com.code.leetcode.offer;

import com.code.leetcode.utils.TreeNode;
import sun.reflect.generics.tree.Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/8/2 10:07
 */
public class The37 {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "[]";
        StringBuilder builder = new StringBuilder("[");
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                builder.append(node.val + ",");
                queue.add(node.left);
                queue.add(node.right);
            } else {
                builder.append("null,");
            }
        }
        builder.append("]");
        return builder.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("[]")) return null;
        String[] strings = data.substring(1, data.length() - 1).split(",");
        TreeNode node = new TreeNode(Integer.parseInt(strings[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(node);
        int index = 1;
        while (!queue.isEmpty()) {
            TreeNode treeNode = queue.poll();

            if (!"null".equals(strings[index])) {
                treeNode.left = new TreeNode(Integer.parseInt(strings[index]));
                queue.add(treeNode.left);
            }
            index++;

            if (!"null".equals(strings[index])) {
                treeNode.right = new TreeNode(Integer.parseInt(strings[index]));
                queue.add(treeNode.right);
            }
            index++;
        }
        return node;
    }


    public static void main(String[] args) {
        The37 the37 = new The37();
        TreeNode node = new TreeNode(0);
        node.left = new TreeNode(1);
        node.right = new TreeNode(2);

        System.out.println(the37.serialize(node));
    }
}
